package zzu.xjc.http;

import zzu.xjc.http.util.Logger;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class HttpServiceExecutor {
    private HashMap<HttpEndPoint, HttpService> services;
    private HashMap<String,HttpSession> sessions;
    /*  The put() method of this services is only called in the main thread (in HttpServer class),thus it is not need to be a ConcurrentHashMap .
        这个map的put()方法仅在main线程中被调用 (HttpServer类中)，因此没必要维护其线程安全 */
    private BufferPool bufferPool;
    private HttpFilterChain filterChain;

    void inject(HashMap<HttpEndPoint, HttpService> map, HttpFilterChain filterChain , HashMap<String,HttpSession> sessionMap,BufferPool bufferPool){
        this.services = map;
        this.filterChain = filterChain;
        this.sessions = sessionMap;
        this.bufferPool = bufferPool;
    }

    HttpResponse execute(HttpRequest request){
        if (request == null){
            return HttpResponse.NotFound404;
        }
        HttpEndPoint endPoint = HttpEndPoint.combine(request.url(), request.method());
        HttpService service = services.get(endPoint);
        if ( service == null){
            return HttpResponse.NotFound404;
        }
        HttpResponse response = HttpResponse.build();
        request.inject(sessions,this);
        request.setResponse(response);
//        response.setRequest(request);
        boolean pass = filterChain.doFilter(request, response);
        if (pass){
            service.serve(request, response);
        }
        return response;
    }


}
